const _ = require("lodash");

const strategies = {
    isNonEmpty: (value, errorMsg) => {
        if (!value || value === "") {
            return errorMsg || "字段不能为空";
        }
    },
    minLength: (value, length, errorMsg) => {
        if (value.length < length) {
            return errorMsg || "字段的最小长度为" + length;
        }
    },
    maxLength: (value, length, errorMsg) => {
        if (value.length > length) {
            return errorMsg || "字段长度不能超过" + length;
        }
    },
    isUrl: (value, errorMsg) => {
        var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        if(!pattern.test(value)) {
            return errorMsg || "请输入正确的url";
        }
    },
    isEmail: (value, errorMsg) => {
        // return errorMsg || "请填写正确的邮箱";
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if(!re.test(value)){
            return errorMsg || "请输入正确的邮箱";
        }
    }
};

class Validator {
    constructor() {
        this.cache = [];
    }

    add(dom, rules) {
        var self = this;
        _.forEach(rules, function(rule){
            (function(rule){
                var strategyAry = rule.strategy.split(":");
                var errorMsg = rule.errorMsg;

                self.cache.push(function(){
                    var strategy = strategyAry.shift();
                    strategyAry.unshift($(dom).val() || $(dom).text() || "");
                    strategyAry.push(errorMsg);
                    return {
                        dom: dom,
                        errorMsg: strategies[strategy].apply(this, strategyAry)
                    };
                });
            })(rule);
        });
    }

    start() {
        for(let i = 0, func; func = this.cache[i++];){
            var result = func();
            if(result.errorMsg){
                return result;
            }
        }
    }
}

export default Validator;